package edu.ptu.communityplatform.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.ptu.communityplatform.domain.entity.ParkingLot;
import edu.ptu.communityplatform.domain.entity.Person;
import edu.ptu.communityplatform.domain.entity.Plot;
import edu.ptu.communityplatform.domain.entity.PlotCar;
import edu.ptu.communityplatform.mapper.*;
import edu.ptu.communityplatform.service.IPlotService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @BelongsProject: communityPlatform
 * @BelongsPackage: edu.ptu.communityplatform.service.impl
 * @Author: HYJ
 * @CreateTime: 2025-04-08  23:36
 * @Description: TODO
 * @Version: 1.0
 */
@Service("plotService")
public class PlotServiceImpl extends ServiceImpl<PlotMapper, Plot> implements IPlotService {

    @Resource
    private PersonMapper personMapper;

    @Resource
    private ParkingLotMapper parkingLotMapper;

    @Resource
    private PlotCarMapper plotCarMapper;

    @Override
    public IPage<Plot> getPage(Integer pageNum, Integer pageSize, String plotName, String plotNo) {
        Page<Plot> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<Plot> wrapper = new LambdaQueryWrapper<>();

        // 构建查询条件
        wrapper.like(StringUtils.isNotBlank(plotName), Plot::getPlotName, plotName).eq(StringUtils.isNotBlank(plotNo), Plot::getPlotNo, plotNo);

        // 执行分页查询
        return this.page(page, wrapper);
    }

    @Transactional
    @Override
    public boolean removeById(Long plotId) {
        // 检查是否存在关联的人员
        if (personMapper.selectById(plotId) != null) {
            personMapper.delete(new LambdaQueryWrapper<Person>()
                    .eq(Person::getPlotId, plotId));
        }
        // 检查是否存在关联的停车位
        if (parkingLotMapper.selectById(plotId) != null) {
            parkingLotMapper.delete(new LambdaQueryWrapper<ParkingLot>()
                    .eq(ParkingLot::getPlotId, plotId));
        }
        // 检查是否存在关联的车辆
        if (plotCarMapper.selectById(plotId) != null) {
            plotCarMapper.delete(new LambdaQueryWrapper<PlotCar>()
                    .eq(PlotCar::getPlotId, plotId));
        }
        return super.removeById(plotId);
    }
}
